package com.aisi.backend.controller;

import com.aisi.backend.domain.RestBean;
import com.aisi.backend.domain.RestCode;
import com.aisi.backend.domain.vo.request.DetailsAccountSaveVo;
import com.aisi.backend.service.ImageService;
import com.aisi.backend.service.impl.ImageServiceImpl;
import com.aisi.backend.utils.WebUtils;
import io.minio.errors.ErrorResponseException;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;

/**
 * @Author: shenjianZ
 * @Date: 2024/5/12 上午8:22
 * @Description:
 */

@WebServlet("/api/image/*")
@MultipartConfig
@Slf4j
public class ImageController extends BaseController {

    private ImageService imageService = new ImageServiceImpl();

    public void uploadImage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer userId = (Integer) request.getAttribute("userId");
        Part filePart = request.getPart("file"); // 获取上传的文件部分
        if (filePart == null) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            WebUtils.writeJson(response, RestBean.failure(RestCode.CODE_BAD_REQUEST));
            return;
        }
        String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // 获取文件名
        String imageURL = imageService.uploadImage(filePart, userId);
        if (imageURL == null) {
            WebUtils.writeJson(response, RestBean.failure(RestCode.IMAGE_UPLOAD_FAILED));
        }
        else {
            WebUtils.writeJson(response, RestBean.success(imageURL));
        }
    }

    public void fetchImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setHeader("Content-Type", "image/jpg");
        String avatarPath = request.getParameter("avatar");
        ServletOutputStream outputStream = response.getOutputStream();
        if (avatarPath.length() <= 13) {
            response.setStatus(404);
            outputStream.println(RestBean.failure(RestCode.FAILURE).toString());
        } else {
            try {
                imageService.fetchImageFromMinio(outputStream, avatarPath);
                response.setHeader("Cache-Control", "max-age=2592000"); // 30 days
            } catch (ErrorResponseException e) {
                if (e.response().code() == 404) {
                    response.setStatus(404);
                    outputStream.println(RestBean.failure(RestCode.FAILURE).toString());
                } else {
                    log.error("Error response from minio", e);
                }
            }
        }
    }

}